package com.xhh.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhh.apis.check.ICheckClient;
import com.xhh.model.check.pojos.Identity;
import com.xhh.model.check.pojos.UserIdentity;
import com.xhh.model.check.vos.CheckedVo;
import com.xhh.model.common.dtos.ResponseResult;
import com.xhh.model.common.enums.AppHttpCodeEnum;
import com.xhh.model.user.pojos.Menu;
import com.xhh.model.user.pojos.Permission;
import com.xhh.model.user.pojos.User;
import com.xhh.model.user.vos.PermissionListVo;
import com.xhh.user.mapper.PermissionMapper;
import com.xhh.user.service.IMenuService;
import com.xhh.user.service.IPermissionService;
import com.xhh.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author xhh
 * @since 2024-08-11
 */
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    private final UserService userService;
    private final ICheckClient checkClient;
    private final IMenuService menuService;

    /**
     * 根据用户id获取所属的权限
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getPermissionByUserId(Long userId) {
        // 查看该用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 获取该用户所属的角色
        ResponseResult result = checkClient.checkIdentity(userId);
        String json = (String) result.getData();
        CheckedVo vo = JSONObject.parseObject(json, CheckedVo.class);
        if (vo == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 获取角色信息
        ResponseResult responseResult = checkClient.getIdentity(userId);
        String str = JSON.toJSONString(responseResult.getData());
        UserIdentity identity = JSONObject.parseObject(str, UserIdentity.class);
        if (identity == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<Menu> menuList;
        // 如果该用户是超级管理员角色则返回所有开启的菜单
        if("204".equals(vo.getIdentityCode())){
            menuList = menuService.lambdaQuery()
                    .eq(Menu::getStatus, 1)
                    .orderByAsc(Menu::getSort)
                    .list();
        }else{
            // 获取该角色所属的菜单id
            List<Permission> permissions = lambdaQuery()
                    .eq(Permission::getRoleId, identity.getIdentityId())
                    .list();
            if (CollUtil.isEmpty(permissions)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 获取菜单
            Set<Integer> menuIds = permissions.stream().map(Permission::getMenuId).collect(Collectors.toSet());
            menuList = menuService.listByIds(menuIds);
            if (CollUtil.isEmpty(menuList)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
        }
        // 递归数据结构
        List<PermissionListVo> permissionListVos = BeanUtil.copyToList(menuList, PermissionListVo.class);
        permissionListVos = bulid(permissionListVos);

        return ResponseResult.okResult(permissionListVos);
    }

    /**
     * 使用递归方法建菜单
     *
     * @param treeNodes
     * @return
     */
    // 整合成泛型,用于工具类
    private static List<PermissionListVo> bulid(List<PermissionListVo> treeNodes) {
        List<PermissionListVo> trees = new ArrayList<>();
        for (PermissionListVo treeNode : treeNodes) {
            if (0 == treeNode.getParentId()) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }
    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    private static PermissionListVo findChildren(PermissionListVo treeNode, List<PermissionListVo> treeNodes) {
//        treeNode.setChildrenTreeNodes(new ArrayList<>());
        for (PermissionListVo it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                it.setLevel(treeNode.getLevel() + 1);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
